package com.lh.mvc.spitter;

import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ContextConfiguration;

import com.lh.mvc.base.BaseDao;

@ContextConfiguration(locations={"classpath:applicationContext.xml"})

public class SpitterDao {

	@Autowired
	@Qualifier("dataSource")
	private DataSource dataSource;
	private static final String SEARCH_ALL = "select * from person";
	private static final String SEARCH_BY_ID = "select * from person where id = ?";
	private static final String UPDATEBYID = "update person set age = ? where id = ?";
	private static final String INSERT_USER = "insert into person(id, name, age, sex, city) values(?,?,?,?,?)";
	   
	private JdbcTemplate jdbcTemplate;
	   
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	public void updatePerson(Person person) {
		jdbcTemplate.update(UPDATEBYID, new Object[]{person.getAge(), person.getId()});
	}

	public List<Map<String, Object>> searchPersons() {
		System.out.println("=====SpitterDAO.searchPersons()=====");
		return jdbcTemplate.queryForList(SEARCH_ALL);
	}  
	
	public Map<String, Object> searchPerson(Person person) {
		return jdbcTemplate.queryForMap(SEARCH_BY_ID, person.getId());
	}

	public int addUser(Person person) {
		System.out.println("=====SpitterDAO.addUser()====="+person);
		System.out.println("person.getSex()===>"+person.getSex());
		System.out.println("person.getCity()===>"+person.getCity());
		
		int i = jdbcTemplate.update(INSERT_USER, Integer.parseInt(person.getId()), person.getName(), Integer.parseInt(person.getAge()), person.getSex(), person.getCity());
		
		return i;
	}
	
}
